﻿using System;
using System.Data.Entity;
using System.Linq;
using Microsoft.Practices.Unity;
using MiniStock.Entities.Common;
using MiniStock.Entities.Stock;

namespace MiniStock.Database
{
    public class EntityDbContext : DbContext
    {

        [InjectionConstructor]
        public EntityDbContext()
        {
        }

        public EntityDbContext(string connectionString)
            : base(connectionString)
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }

        public DbSet<Customer> Customers { get; set; }
        public DbSet<Product> Products { get; set; }
        public DbSet<Order> Orders { get; set; }
        public DbSet<OrderItem> OrderItems { get; set; }

        public EntityBase GetEntityByHash(string hash)
        {
            var parts = hash.Split('|');

            var entityType = SerializationHelper.KnownEntityTypes.FirstOrDefault(i => i.Name == parts[0]);
            var result = this.Set(entityType).Find(Guid.Parse(parts[1]));

            return result as EntityBase;
        }
    }
}
